package com.mybatis.boost.generator.xml;

import org.mybatis.generator.api.dom.OutputUtilities;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Element;

import java.util.Collections;

/**
 * @author jearton
 * @since 2016/11/22
 */
public class XmlElement extends org.mybatis.generator.api.dom.xml.XmlElement {

    public XmlElement(String name) {
        super(name);
    }

    public XmlElement(org.mybatis.generator.api.dom.xml.XmlElement original) {
        super(original);
    }

    @Override
    public String getFormattedContent(int indentLevel) {
        StringBuilder sb = new StringBuilder();

        OutputUtilities.xmlIndent(sb, indentLevel);
        sb.append('<');
        sb.append(super.getName());

        Collections.sort(super.getAttributes());
        for (Attribute att : super.getAttributes()) {
            sb.append(' ');
            sb.append(att.getFormattedContent());
        }

        if (super.getElements().size() > 0) {
            sb.append(">"); //$NON-NLS-1$
            for (Element element : super.getElements()) {
                OutputUtilities.newLine(sb);
                if (element instanceof org.mybatis.generator.api.dom.xml.XmlElement) {
                    sb.append(new XmlElement((org.mybatis.generator.api.dom.xml.XmlElement) element)
                            .getFormattedContent(indentLevel + 2));
                } else {
                    sb.append(element.getFormattedContent(indentLevel + 2));
                }
            }
            OutputUtilities.newLine(sb);
            OutputUtilities.xmlIndent(sb, indentLevel);
            sb.append("</"); //$NON-NLS-1$
            sb.append(super.getName());
            sb.append('>');
        } else {
            sb.append("/>"); //$NON-NLS-1$
        }
        return sb.toString();
    }
}
